﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NLog.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Helpers
{
    /// <summary>
    /// 日志帮助类，依赖DiHelper
    /// </summary>
    public class LogHelper
    {
        
        private static readonly object ILoggerLocker = new object();
        private static ILogger _logger;
        private readonly ILoggerFactory _loggerFactory;
        public LogHelper(ILoggerFactory loggerFactory)
        {
            this._loggerFactory = loggerFactory;
        }

        /// <summary>
        /// 日志
        /// </summary>
        public  ILogger Logger
        {
            get
            {
                if (_logger == null)
                {
                    lock (ILoggerLocker)
                    {
                        if (_logger == null)
                        {
                            _logger = CreateCurrentClassLogger();
                        }
                    }
                }
                return _logger;
            }
        }


        public ILogger<T> CreateLogger<T>()
        {
            return _loggerFactory.CreateLogger<T>();
        }

        public ILogger CreateCurrentClassLogger()
        {
            StackTrace trace = new StackTrace();
            var type = trace.GetFrame(1).GetMethod().DeclaringType;
            return _loggerFactory.CreateLogger(type);
        }


    }

}
